<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--      <div v-if="crud.props.searchToggle">-->
      <!--        &lt;!&ndash; 搜索 &ndash;&gt;-->
      <!--        <el-input-->
      <!--          v-model="query.blurry"-->
      <!--          size="small"-->
      <!--          clearable-->
      <!--          placeholder="输入名称或者描述搜索"-->
      <!--          style="width: 200px;"-->
      <!--          class="filter-item"-->
      <!--          @keyup.enter.native="crud.toQuery" />-->
      <!--        <el-date-picker-->
      <!--          v-model="query.createTime"-->
      <!--          :default-time="['00:00:00','23:59:59']"-->
      <!--          type="datetimerange"-->
      <!--          range-separator=":"-->
      <!--          size="small"-->
      <!--          class="date-item"-->
      <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--          start-placeholder="开始日期"-->
      <!--          end-placeholder="结束日期"-->
      <!--        />-->
      <!--        <rrOperation :crud="crud" />-->
      <!--      </div>-->
      <crudOperation :permission="permission" />
    </div>
    <!-- 表单渲染 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="520px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" style="width: 145px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择状态"
            style="width: 180px"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="crud.submitCU"
        >确认</el-button
        >
      </div>
    </el-dialog>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col
        :xs="24"
        :sm="24"
        :md="16"
        :lg="16"
        :xl="17"
        style="margin-bottom: 10px"
      >
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table
            ref="table"
            v-loading="crud.loading"
            highlight-current-row
            style="width: 100%"
            :data="crud.data"
            @selection-change="crud.selectionChangeHandler"
            @current-change="handleCurrentChange"
          >
            <!-- <el-table-column
              :selectable="checkboxT"
              type="selection"
              width="55"
            /> -->
            <el-table-column
              v-if="columns.visible('name')"
              prop="name"
              label="名称"
            />
            <!-- <el-table-column
              v-if="columns.visible('status')"
              :show-overflow-tooltip="true"
              prop="status"
              label="状态"
            /> -->
            <el-table-column
              v-if="columns.visible('createAt')"
              :show-overflow-tooltip="true"

              prop="createAt"
              label="创建日期"
            />
            <el-table-column
              v-permission="['admin', 'roles:edit', 'roles:del']"
              label="操作"
              width="130px"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <udOperation :data="scope.row" :permission="permission" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <!-- 菜单授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip
              class="item"
              effect="dark"
              content="选择指定角色分配菜单"
              placement="top"
            >
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存
            </el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            accordion
            show-checkbox
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudRoles from '@/api/permission/role'
import { getDepts } from '@/api/system/dept'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { treeList } from '../../../api/permission/menu'
import {
  getPermissionByRole,
  rolePermissionUpdate
} from '../../../api/permission/role'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '角色',
  url: '/admin/role/getRole',
  crudMethod: { ...crudRoles }
})
const defaultForm = { id: null, name: null, status: 0 }
export default {
  name: 'Role',
  components: { Treeselect, crudOperation, rrOperation, udOperation },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      defaultProps: { children: 'children', label: 'name' },
      dateScopes: ['全部', '本级', '自定义'],
      level: 3,
      currentId: 0,
      menuLoading: false,
      menus: [],
      menuIds: [],
      statusList: [
        {
          value: 0,
          label: '启用'
        },
        {
          value: -2,
          label: '禁用'
        }
      ],
      permission: {
        add: ['admin', 'role:add'],
        edit: ['admin', 'role:edit'],
        del: ['admin', 'role:del']
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
        // note: [{ required: true, message: "请输入备注信息", trigger: "blur" }],
      }
    }
  },
  created() {
    this.getMenus()
  },
  methods: {
    [CRUD.HOOK.afterRefresh]() {
      this.$refs.menu.setCheckedKeys([])
    },
    [CRUD.HOOK.beforeToAdd](crud) {
      this.$set(crud.form, 'createAt', null)
      this.$set(crud.form, 'status', 0)
      this.$set(crud.form, 'id', null)
      this.$set(crud.form, 'name', null)
    },
    [CRUD.HOOK.beforeToEdit](crud) {
      console.log(crud.form)
      // const str = parseTime(crud.form.startDate);
      // const strend = parseTime(crud.form.endDate);

      this.$set(crud.form, 'createAt', null)
    },
    // 获取所有菜单
    getMenus() {
      treeList().then((res) => {
        if (res.code == 0) {
          this.menus = res.data
        }
      })
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中
        this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.id
        // this.showButton = this.level <= val.level
        this.showButton = true
        // 初始化
        this.menuIds = []
        // 菜单数据需要特殊处理
        getPermissionByRole({ id: val.id }).then((res) => {
          if (res.code == 0) {
            const menuIds = res.data.privilegeList.map((data, index) => {
              return data && data.id
            })
            this.$refs['menu'].setCheckedKeys(menuIds)
          }
        })
      }
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true
      const role = { id: this.currentId, privileges: [], parentIds: [] }
      // 得到半选的父节点数据，保存起来
      this.$refs.menu.getHalfCheckedNodes().forEach(function(data, index) {
        const menu = { id: data.id }
        role.parentIds.push(menu.id)
      })
      // 得到已选中的 key 值
      this.$refs.menu.getCheckedKeys().forEach((menu) => {
        // const menu = { id: data }
        role.privileges.push(menu)
      })
      rolePermissionUpdate(role)
        .then((res) => {
          if (res.code == 0) {
            this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
            this.menuLoading = false
          }
        })
        .catch((err) => {
          this.menuLoading = false
          console.log(err.response.data.message)
        })
    },
    // 获取部门数据
    getDepts() {
      getDepts({ enabled: true }).then((res) => {
        this.depts = res.content
      })
    },
    // 如果数据权限为自定义则获取部门数据
    changeScope() {
      if (this.form.dataScope === '自定义') {
        this.getDepts()
      }
    },
    checkboxT(row, rowIndex) {
      return row.level >= this.level
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .el-input-number .el-input__inner {
  text-align: left;
}
</style>
